package com.opgea.crm.repository.security;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.opgea.crm.domain.entities.security.ResourceDetails;

@Repository
public class ResourceDetailsRepositoryImpl implements ResourceDetailsRepository{

	@PersistenceContext
	EntityManager em;
	
	@Override
	@Transactional
	public void create(ResourceDetails resourceDetails) {
		em.persist(resourceDetails);
	}

	@Override
	public ResourceDetails find(Long id) {
		return em.find(ResourceDetails.class, id);
	}

	@Override
	public List<ResourceDetails> findAll() {
		String query = "SELECT r FROM ResourceDetails r";
		return em.createQuery(query, ResourceDetails.class).getResultList();
	}

	@Override
	@Transactional
	public void update(ResourceDetails resourceDetails) {
		if (em.find(ResourceDetails.class, resourceDetails.getId()) == null) {
	        throw new IllegalArgumentException("Unknown ResourceDetails Id: " + resourceDetails.getId());
	      }
		ResourceDetails managedResourceDetails = em.merge(resourceDetails);
		//em.refresh(managedResourceDetails);
	}

	@Override
	public void remove(Long id) {
	}

	@Override
	public List<ResourceDetails> findByRole(Long roleId) {
		String query = "SELECT r FROM ResourceDetails r WHERE r.role.id = "+roleId;
		return em.createQuery(query, ResourceDetails.class).getResultList();
	}

}
